﻿using HandyControl.Tools.Extension;
using Microsoft.Extensions.DependencyInjection;
using System.ComponentModel;
using System.Windows;
using WpfApp.Uers;
using WpfApp.ViewModels;
using WpfApp.Views;
using MessageBox = HandyControl.Controls.MessageBox;
using Window = System.Windows.Window;

namespace WpfApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly UserManager _userManager;

        private readonly IServiceProvider _serviceProvider;

        private MainWindowViewModel? _vm = null!;

        public MainWindow(
            UserManager userManager,
            IServiceProvider serviceProvider
         )
        {
            InitializeComponent();
            _userManager = userManager;
            GlobalIdentity.ElapsedAsync += GlobalIdentity_ElapsedAsync;
            GlobalIdentity.UnregisteredAsync += GlobalIdentity_UnregisteredAsync;
            this.Loaded += MainWindow_Loaded;
            _serviceProvider = serviceProvider;
            this.Closed += MainWindow_Closed;
            this.DataContextChanged += MainWindow_DataContextChanged;
        }

        private void MainWindow_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            _vm = this.DataContext as MainWindowViewModel;
        }

        private void MainWindow_Closed(object? sender, EventArgs e)
        {
            _vm?.OnClose();
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.UserEditGrid.IsEnabled = false;
            this.MesConfigButton.IsEnabled = false;

            if (!string.IsNullOrWhiteSpace(this.ResourceIdTextBox.Text))
            {
                this.ConnectionButton.Command.Execute(this.ConnectionButton);
            }
        }

        private void GlobalIdentity_UnregisteredAsync(object? sender, EventArgs e)
        {
            this.Dispatcher.Invoke(() =>
            {
                this.MesConfigButton.IsEnabled = false;
                this.AuthButton.IsEnabled = true;
                this.UserEditGrid.IsEnabled = false;
                this.AuthTextBlock.Text = $"未认证";
            });
        }

        private void GlobalIdentity_ElapsedAsync(object? sender, AuthTimeoutEventArgs e)
        {
            this.Dispatcher.Invoke(() =>
            {
                this.AuthTextBlock.Text = $"{e.TimeCount}s";
            });
        }

        private void OnAuthUser(object sender, RoutedEventArgs e)
        {
            var password = this.PasswordBox.Password;
            var result = _userManager.Auth(password ?? string.Empty, out var user);

            if (!result)
            {
                MessageBox.Show("密码错误！", "提示");
            }
            else
            {
                this.MesConfigButton.IsEnabled = true;
                this.UserEditGrid.IsEnabled = true;
                this.AuthButton.IsEnabled = false;
                this.PasswordBox.Password = "";
                GlobalIdentity.SetAuth(user);
            }
        }

        private void UserManageButton_Click(object sender, RoutedEventArgs e)
        {
            var window = _serviceProvider.GetRequiredService<UserManagerWindow>();
            window.ShowDialog();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (!GlobalIdentity.IsAuth)
            {
                e.Cancel = true;
                MessageBox.Show("需要认证后才能关闭程序！", "用户提示");
            }
            else
            {
                base.OnClosing(e);
                // 主窗口关闭后，关闭 mes 配置窗口
                this._mesConfigWindow?.Close();
            }
        }

        private void AppNotifyIcon_Click(object sender, RoutedEventArgs e)
        {
            if (this.WindowState == WindowState.Minimized)
            {
                this.WindowState = WindowState.Normal;
                this.Show();
                this.Activate();
            }
        }

        protected override void OnStateChanged(EventArgs e)
        {
            if (this.WindowState == WindowState.Minimized)
            {
                this.AppNotifyIcon.Show();
                ShowInTaskbar = false;
            }
            else
            {
                ShowInTaskbar = true;
                this.AppNotifyIcon.Hide();
            }
            base.OnStateChanged(e);
        }

        private Window? _mesConfigWindow;

        private void MesConfigButton_Click(object sender, RoutedEventArgs e)
        {
            _mesConfigWindow = _serviceProvider.GetRequiredService<MesConfigWindow>();
            _mesConfigWindow.Loaded -= MesConfigWindow_Loaded;
            _mesConfigWindow.Loaded += MesConfigWindow_Loaded;
            _mesConfigWindow.Closed += MesConfigWindow_Closed;
            _mesConfigWindow.Left = this.Left + 20;
            _mesConfigWindow.Top = this.Top + 20;
            _mesConfigWindow.Show();
        }

        private void MesConfigWindow_Closed(object? sender, EventArgs e)
        {
            this.MesConfigButton.IsEnabled = true;
            this.InboundButton.IsEnabled = true;
            _mesConfigWindow = null;
        }

        private void MesConfigWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.InboundButton.IsEnabled = false;
            this.MesConfigButton.IsEnabled = false;
        }
    }
}